package com.rongshe.web.controller.hotel;

import java.util.ArrayList;
import java.util.Collections;
import java.util.List;
import java.util.stream.Collectors;
import javax.servlet.http.HttpServletResponse;

import com.rongshe.common.constant.MessageConstants;
import com.rongshe.common.core.domain.entity.SysUser;
import com.rongshe.common.utils.DateUtils;
import com.rongshe.common.utils.StringUtils;
import com.rongshe.system.domain.MessageDTO;
import com.rongshe.system.service.ISysMessageService;
import com.rongshe.system.service.ISysUserService;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.PutMapping;
import org.springframework.web.bind.annotation.DeleteMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import com.rongshe.common.annotation.Log;
import com.rongshe.common.core.controller.BaseController;
import com.rongshe.common.core.domain.AjaxResult;
import com.rongshe.common.enums.BusinessType;
import com.rongshe.hotel.domain.RsBooking;
import com.rongshe.hotel.service.IRsBookingService;
import com.rongshe.common.utils.poi.ExcelUtil;
import com.rongshe.common.core.page.TableDataInfo;

/**
 * 行程Controller
 *
 * @author rongshe
 * @date 2025-02-17
 */
@RestController
@RequestMapping("/hotel/booking")
public class RsBookingController extends BaseController {
    @Autowired
    private IRsBookingService rsBookingService;
    @Autowired
    private ISysUserService  userService;
    /**
     * 查询行程列表
     */
    @GetMapping("/list")
    public TableDataInfo list(RsBooking rsBooking) {
        //如果是用户查询，待出行订单 为 待出行+已确认+已出发
        SysUser user = getLoginUser().getUser();
        if (null != user.getUserType() && user.getUserType().equals("01")) {
            rsBooking.setUserId(user.getUserId());
            if (rsBooking.getStatus().equals("1")) {
                rsBooking.setStatus(null);
                rsBooking.setStatusIn("1,4,5");
            }
        }
        startPage();
        List<RsBooking> list = rsBookingService.selectRsBookingList(rsBooking);
        return getDataTable(list);
    }

    /**
     * 导出行程列表
     */
    @PreAuthorize("@ss.hasPermi('hotel:booking:export')")
    @Log(title = "行程", businessType = BusinessType.EXPORT)
    @PostMapping("/export")
    public void export(HttpServletResponse response, RsBooking rsBooking) {
        List<RsBooking> list = rsBookingService.selectRsBookingList(rsBooking);
        ExcelUtil<RsBooking> util = new ExcelUtil<RsBooking>(RsBooking.class);
        util.exportExcel(response, list, "行程数据");
    }

    /**
     * 获取行程详细信息
     */
    @PreAuthorize("@ss.hasPermi('hotel:booking:query')")
    @GetMapping(value = "/{id}")
    public AjaxResult getInfo(@PathVariable("id") Long id) {
        return success(rsBookingService.selectRsBookingById(id));
    }

    /**
     * 新增行程
     */
    @Log(title = "行程", businessType = BusinessType.INSERT)
    @PostMapping
    public AjaxResult add(@RequestBody RsBooking rsBooking) {
        rsBooking.setUserId(getLoginUser().getUserId());
        rsBooking.setStatus("1");
        int result = rsBookingService.insertRsBooking(rsBooking);
        createMessage(rsBooking, rsBooking.getStatus());
        return toAjax(result);
    }

    /**
     * 修改行程
     */
    @Log(title = "行程", businessType = BusinessType.UPDATE)
    @PutMapping
    public AjaxResult edit(@RequestBody RsBooking rsBooking) {
        if (StringUtils.isEmpty(rsBooking.getStatus())) {
            rsBooking.setStatus("1");
        }
        int result = rsBookingService.updateRsBooking(rsBooking);
//        createMessage(rsBooking, rsBooking.getStatus());
        return toAjax(result);
    }

    /**
     * 删除行程
     */
    @Log(title = "行程", businessType = BusinessType.DELETE)
    @DeleteMapping("/{ids}")
    public AjaxResult remove(@PathVariable Long[] ids) {
        return toAjax(rsBookingService.deleteRsBookingByIds(ids));
    }


    @Autowired
    private ISysMessageService messageService;

    /**
     * 订单状态变更并发送消息通知
     */
    private void createMessage(RsBooking rsBooking, String status) {

        // 3. 构建消息内容
        String title = "";
        StringBuilder content = new StringBuilder();
        switch (status) {
            case "1": // 待出行
                title += "行程待出行通知";
                break;
            case "2": // 已完成
                title += "行程已完成通知";
                break;
            case "3": // 已取消
                title += "行程已取消通知";
                break;
            case "4": // 已确认
                title += "行程已确认通知";
                break;
            case "5": // 已出发
                title += "行程已出发通知";
                break;
            default:
                break;
        }
        content.append("行程类型：" + (rsBooking.getType().equals("1") ? "预约接站" : "预约送站") + "<br>");
        content.append("车站名称：" + rsBooking.getStationName() + "<br>");
        content.append("出行时间：" + DateUtils.parseDateToStr(DateUtils.YYYY_MM_DD_HH_MM_SS, rsBooking.getArrivalTime()) + "<br>");
        content.append("乘客姓名：" + rsBooking.getUsername() + "<br>");
        content.append("联系方式：" + rsBooking.getPhone() + "<br>");
        content.append("出行人数：" + rsBooking.getPersonCount() + "<br>");

        // 4. 发送消息通知
        MessageDTO messageDTO = new MessageDTO();
        messageDTO.setTitle(title);
        messageDTO.setContent(content.toString());
        messageDTO.setInfoId(rsBooking.getId());
        messageDTO.setMessageType(MessageConstants.MESSAGE_TYPE_BOOKING);    // 订单消息
        messageDTO.setSenderType(MessageConstants.SENDER_TYPE_SYSTEM);     // 系统发送
        messageDTO.setImportance(MessageConstants.IMPORTANCE_NORMAL);   // 重要消息
        List<SysUser> sysUsers = userService.selectWebUserList();
        List<Long> receiverIds = sysUsers.stream().map(SysUser::getUserId).collect(Collectors.toList());
        messageDTO.setReceiverIds(receiverIds);

        messageService.sendMessage(messageDTO);
    }

//    /**
//     * 订单即将到期提醒
//     */
//    @Scheduled(cron = "0 0 10 * * ?") // 每天上午10点执行
//    public void checkOrderExpiration() {
//        // 1. 查询即将到期的订单（比如明天到期）
//        List<OrderVO> expiringOrders = orderMapper.selectExpiringOrders();
//
//        // 2. 发送提醒消息
//        for (OrderVO order : expiringOrders) {
//            MessageDTO messageDTO = new MessageDTO();
//            messageDTO.setTitle("订单到期提醒");
//            messageDTO.setContent(String.format(
//                    "您的订单（编号：%s）将于明天到期，请注意办理退房手续。\n" +
//                            "房间号：%s\n" +
//                            "退房时间：%s\n" +
//                            "如需延长住宿，请及时联系前台。",
//                    order.getOrderNo(),
//                    order.getRoomNo(),
//                    order.getEndTime()
//            ));
//            messageDTO.setMessageType(MessageConstants.MESSAGE_TYPE_ORDER);
//            messageDTO.setSenderType(MessageConstants.SENDER_TYPE_SYSTEM);
//            messageDTO.setImportance(MessageConstants.IMPORTANCE_URGENT);  // 紧急消息
//            messageDTO.setReceiverIds(Collections.singletonList(order.getUserId()));
//
//            messageService.sendMessage(messageDTO);
//        }
//    }
}
